let city = ''
$.ajax({
  url: "../../../js/city.json",
  data: { action: "jQueryAjax" },
  type: "GET",
  async: false,
  success: function (data) {
    city = data
  },
  //返回数据的格式
  dataType: "json"
})
const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      form: {},//提交的表单
      isEdit: false,
      loading: false,
      city,
      // 被选中的市数据
      cityList: [],
      // 被选中的县数据
      areaList: [],
      isdisabled: true,
      selectProvince: {},
      selectCity: {},
      selectArea: {},
      address: '',
      loading: false,
      dialogVisible:false,
      dialogImageUrl:'',
      calculation:[],
      isCalculation:false
    }
  },
  mounted() {
    this.getData()
    this.getEnterpriseData()
  },
  computed: {
    maskIDCard() {
      return function (idCard) {
        if (!idCard || idCard.length < 18) {
          return idCard;
        }
        return idCard.replace(/(\d{2})(\d{16})(\d{2})/, '$1****************$2');
      }
    }
  },
  methods: {
    getData(){
      const _this = this
      $.ajax({
        url: DomainName + '/GoodsFileInquiry',
        type: 'POST',
        data: {
          Data:'calculation_info'
        },
        success: function (result) {
          _this.calculation = result;
        }
      })
    },
    add_enterprise_legal_person() {
      this.form.Children.enterprise_legal_person.push({
        Enterprise_Legal_Person_SerialNumber: "",
        Enterprise_Info_SerialNumber: this.form.Enterprise_Info_SerialNumber,
        Legal_Person: '',//法人姓名
        ID_Number: '',//法人身份证号
        Mobile: '',//法人手机号
      })
    },
    add_enterprise_account() {
      this.form.Children.enterprise_account.push({
        Enterprise_Account_SerialNumber: "",
        Enterprise_Info_SerialNumber:this.form.Enterprise_Info_SerialNumber,
        Account_Name: '',
        Bank_Name: '',//开户行
        Account_Number: '',//银行账号
      })
    },
    add_enterprise_technology(){
      this.form.Children.enterprise_technology.push({
        Enterprise_Technology_SerialNumber:"",
        Enterprise_Info_SerialNumber:this.form.Enterprise_Info_SerialNumber,
        Enterprise_Technology_Explain:""
      })
    },
    remove_enterprise_account() {
      if (this.form.Children.enterprise_account.filter(item => item.Row_Status != '1').length > 1) {
        let i = this.form.Children.enterprise_account.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.enterprise_account.filter(item => item.Row_Status != '1')[i]
        if(!Object.keys(obj).some(item => item.includes('_Original'))){
          this.form.Children.enterprise_account.pop();
        } else {
          this.$confirm('警告！此操作将删除一条已有的银行账户信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.enterprise_account.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    remove_enterprise_technology(){
      if (this.form.Children.enterprise_technology.filter(item => item.Row_Status != '1').length > 0) {
        let i = this.form.Children.enterprise_technology.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.enterprise_technology.filter(item => item.Row_Status != '1')[i]
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.form.Children.enterprise_technology.pop()
        } else {
          this.$confirm('警告！此操作将删除一条已有的技术说明, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.enterprise_technology.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
        
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    editMember() {
      if (this.isEdit) {
        var _this = this
        if (!this.loading) {
          const { add, modify } = _this.deal()
          let data = {}
          if (add == null) {
            data = { Data: JSON.stringify({ Modify: { enterprise_info: [modify] } }) }
          } else {
            data = {
              Data: JSON.stringify({ Modify: { enterprise_info: [modify] }, Add: { enterprise_info: [add] } }),
            }
          }
          _this.loading = true
          $.ajax({
            url: `${DomainName}/getEditAction?token=${$.cookie("token")}`,
            type: 'POST',
            data,
            success: function (res) {
              if (res.Status === 'success') {
                _this.getEnterpriseData(()=>{
                  _this.$message.success("提交成功")
                })
              } else {
                _this.$message.error("提交失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        }
      } else {
        this.isEdit = !this.isEdit
      }
    },
    getEnterpriseData(callback) {
      const _this = this
      $.ajax({
        url: DomainName + '/getEnterpriseInfoIDAction',
        type: 'POST',
        data: {
          token: $.cookie("token")
        },
        success: function (result) {
          _this.form = result.enterprise_info[0]
          let arr = _this.form.Enterprise_Address.split('/')
          _this.selectProvince = _this.city.filter(item => {
            return item.label == arr[0]
          })[0]
          _this.cityList = _this.selectProvince.children
          _this.selectCity = _this.cityList.filter(item => {
            return item.label == arr[1]
          })[0]
          _this.areaList = _this.selectCity.children
          _this.selectArea = _this.areaList.filter(item => {
            return item.label == arr[2]
          })[0]
          _this.address = arr[3]
          _this.isdisabled = false
          if(_this.form.Calculation_SerialNumber!=''){
            _this.isCalculation = true
          }
          if (callback) {
            callback();
          }
        },
        complete: function (XMLHttpRequest) {
          _this.isEdit = false
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)
      let add_enterprise_legal_person = [], modify_enterprise_legal_person = []
      let add_enterprise_account = [], modify_enterprise_account = []
      let add_enterprise_technology = [], modify_enterprise_technology = []
      for (const i in modify.Children.enterprise_legal_person) {
        const obj = modify.Children.enterprise_legal_person[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_enterprise_legal_person.push(obj)
        } else {
          modify_enterprise_legal_person.push(obj)
        }
      }
      for (const i in modify.Children.enterprise_account) {
        const obj = modify.Children.enterprise_account[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_enterprise_account.push(obj)
        } else {
          modify_enterprise_account.push(obj)
        }
      }
      for (const i in modify.Children.enterprise_technology) {
        const obj = modify.Children.enterprise_technology[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_enterprise_technology.push(obj)
        } else {
          modify_enterprise_technology.push(obj)
        }
      }
      add.Children.enterprise_legal_person = add_enterprise_legal_person
      add.Children.enterprise_account = add_enterprise_account
      add.Children.enterprise_technology = add_enterprise_technology
      modify.Children.enterprise_legal_person = modify_enterprise_legal_person
      modify.Children.enterprise_account = modify_enterprise_account
      modify.Children.enterprise_technology = modify_enterprise_technology
      if (add_enterprise_legal_person.length == 0 && add_enterprise_account.length == 0 && add_enterprise_technology.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    selectProvinceFun(event) {
      console.log(event)
      if (event) {
        this.cityList = event.children
      } else {
        this.cityList = []
      }
      this.areaList = []
    },
    selectCityFun(event) {
      console.log(event)
      if (event) {
        this.areaList = event.children
      } else {
        this.areaList = []
      }
    },
    selectAreaFun(event) {
      if (event) {
        console.log(event)
        this.isdisabled = false
      } else {
        this.isdisabled = true
      }
    },
    selectAddress(event) {
      if (event && event != '' && this.selectArea.label != undefined) {
        this.form.Enterprise_Address = this.selectProvince.label + '/'
          + this.selectCity.label + '/'
          + this.selectArea.label + '/'
          + this.address
      }
    },
    handleRemove(){
      this.form.Enterprise_Logo = ''
    },
    handlePictureCardPreview(file){
      this.dialogVisible = true
      this.dialogImageUrl = file
    },
    uploadFront(file) {
      let _this = this
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      new Compressor(file, {
        quality: num,
        success(file) {
          console.log(file.size)
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/BusinessPIC',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name,
                logo:'logo'
              },
              complete: function (XMLHttpRequest) {
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                _this.form.Enterprise_Logo = e.target.result
                if (Result.Status == "success") {
                  _this.form.Enterprise_Logo = Result.Picture_Url
                  _this.$message.success('上传成功')
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    }
  }
})